package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	router := gin.Default()
	router.GET("/query_bind", QueryBind) //postman:param:
	router.POST("/form_bind", FormBind)  //postman:body:x-www-form-urlencoded
	router.POST("/json_bind", JsonBind)  //postman:body:row:json
	router.GET("/uri_bind/:name/:age/:addr", UriBind) //url: /query_bind/:name/:age/:addr
	router.Run()
}

//绑定form和query和json可以使用form
type UserForm struct {
	Name string `form:"name"`
	Age  int    `form:"age"`
	Addr string `form:"addr"`
}

//绑定json可以使用json
type UserJson struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
	Addr string `json:"addr"`
}

//绑定uri可以使用uri
type UserUri struct {
	Name string `uri:"name"`
	Age  int    `uri:"age"`
	Addr string `uri:"addr"`
}

func FormBind(ctx *gin.Context) {
	var user UserForm
	err := ctx.ShouldBind(&user)
	fmt.Println(err, user.Age, user.Name, user.Addr)
	if err != nil {
		ctx.String(http.StatusNotFound, "Form绑定失败")
		return
	}
	ctx.String(http.StatusOK, "Form绑定成功")
	return
}
func QueryBind(ctx *gin.Context) {
	var user UserForm
	err := ctx.ShouldBind(&user)
	fmt.Println(err, user.Age, user.Name, user.Addr)
	if err != nil {
		ctx.String(http.StatusNotFound, "Query绑定失败")
		return
	}
	ctx.String(http.StatusOK, "Query绑定成功")
	return
}

//使用UserForm或者UserJson这个结构体
func JsonBind(ctx *gin.Context) {
	var user UserForm
	err := ctx.ShouldBind(&user)
	fmt.Println(err, user.Age, user.Name, user.Addr)
	if err != nil {
		ctx.String(http.StatusNotFound, "json绑定失败")
		return
	}
	ctx.String(http.StatusOK, "json绑定成功")
	return
}

//使用UserUri这个结构体
func UriBind(ctx *gin.Context) {
	var user UserUri
	err := ctx.ShouldBindUri(&user)
	fmt.Println(err, user.Age, user.Name, user.Addr)
	if err != nil {
		ctx.String(http.StatusNotFound, "uri绑定失败")
		return
	}
	ctx.String(http.StatusOK, "uri绑定成功")
	return
}
